CompletableFuture API 全面介绍

API 整体介绍

接口的名称

CompletableFuture 的 API 命名极其有规律,掌握了它的命名范式,就能做到 “见名知意”。

API 命名三元组(核心范式):

  • …Apply…:入参为 Function $\rightarrow$ 有输入,有返回值。
  • …Accept…:入参为 Consumer $\rightarrow$ 有输入,无返回值(纯消费)。
  • …Run…:入参为 Runnable $\rightarrow$ 无输入,无返回值(仅执行动作)。

此外,绝大多数方法都有 3 种重载形式:

  • thenXxx(fn):在前序任务的执行线程(或主线程)中同步执行。
  • thenXxxAsync(fn):提交到认线程池(ForkJoinPool.commonPool())异步执行。
  • thenXxxAsync(fn, executor):提交到自定义线程池异步执行(生产推荐)。


五类核心 API

  • 任务创建与启动 API(入口):以 supplyAsync 为例,它的内部会立即将你的 Lambda 表达式封装为一个 AsyncSupply 任务,并调用 executor.execute(task) 提交给线程池(未指定线程池时默认使用 ForkJoinPool.commonPool())。一旦提交成功,只要线程池里有空闲的 Worker 线程,该任务就会立刻在子线程中开始执行,主线程则继续向下运行,二者并发执行。supplyAsync 返回的 CompletableFuture 对象本质上是一个接收结果的“容器”。哪怕你后续没有任何代码去读取这个 Future,”task02” 也已经在子线程中被打印出来了。
    • 异步带返回值:supplyAsync,Supplier $\rightarrow$ CompletableFuture<U>
    • 异步无返回值:runAsync,Runnable $\rightarrow$ CompletableFuture<Void>
    • 已知结果直接封装:completedFuture,U $\rightarrow$ CompletableFuture<U>
  • 单任务依赖转换 API(串行链式调用),用于在上一个任务完成后,紧接着执行下一个任务(类似于 Stream 的 map / forEach)。[ Task A ] ──(完成)──> [ thenApply / thenAccept / thenRun ] ──> [ Task B ]
    • thenApply(Function fn):Function $\rightarrow$ CompletionStage。拿到上一步的结果,做数据转换,返回新结果(如 JSON 字符串转对象)。
    • thenAccept(Consumer c):Consumer $\rightarrow$ CompletionStage。拿到上一步的结果,直接消费(如将查询到的数据写入数据库/打印)。
    • thenRun(Runnable r):Runnable $\rightarrow$ CompletionStage。不关心上一步的结果,只要上一步做完了,就接着做这件事(如更新 UI/发通知)。
  • 多任务组合与编排 API(并行 / 嵌套组合),这是 CompletableFuture 最强大的地方,用于解决复杂的异步依赖关系。
    • 一对一组合(依赖/扁平化):类似于 Stream 的 flatMap,用于解决嵌套异步任务(如任务 A 的返回值是一个 CompletableFuture)。
      • thenCompose(Function<T, CompletionStage<U>> fn):类似于 Stream 的 flatMap,用于解决嵌套异步任务(如任务 A 的返回值是一个 CompletableFuture)。典型应用比如先异步获取用户 ID,拿到 ID 后再异步查询该用户的订单列表。
    • 双任务并行聚合(AND 关系:两者都完成)
      • thenCombine(f2, BiFunction):合并 A 和 B 的结果生成新结果(如并发查商品和库存,合并为商品详情)。
      • thenAcceptBoth(f2, BiConsumer):拿到 A 和 B 的结果一起消费,无返回值。
      • runAfterBoth(f2, Runnable):A 和 B 都跑完了,触发一个收尾动作。
    • 双任务竞速(OR 关系:任意一个完成,两个异步任务并行执行,谁先跑完就用谁)
      • applyToEither(f2, Function):谁先完就拿到谁的结果,经过转换后返回新值。
      • acceptEither(f2, Consumer):谁先完就拿到谁的结果,直接消费。
      • runAfterEither(f2, Runnable):任意一个完,直接触发后续动作。
    • 多任务批量控制(N 个任务)
      • allOf(CompletableFuture… cfs):等待所有传入的 Future 全部完成,返回 CompletableFuture。比如并发调用 5 个微服务,等 5 个全部返回后再进行页面渲染。
      • anyOf(CompletableFuture… cfs):任意一个传入的 Future 完成即触发。返回 CompletableFuture。比如同时向 3 个镜像服务器请求同一个文件,谁最快响应就用谁。
  • 异常处理 API,异步任务中的异常不会直接抛在主线程,必须通过专门的 API 捕获。
    • exceptionally(Function fn):仅异常时触发,类似于 catch。
    • handle(BiFunction fn):无论成功失败均触发, (result, ex) $\rightarrow$ CompletionStage,类似于 try-catch-finally。
    • whenComplete(BiConsumer fn):无论成功失败均触发,(result, ex) $\rightarrow$ CompletionStage,类似于 finally。
  • 结果获取与手动操控 API:用于阻塞获取结果,或者外部手动完成这个 Future。
    • get() / get(timeout, unit):阻塞获取,需要抛出检查异常,更推荐带超时的阻塞获取,防止死等。
    • getNow(valueIfAbsent):非阻塞获取,不需要抛出检查异常。如果任务已完成则返回结果,若未完成,立即返回传入的兜底默认值。
    • join():阻塞获取,不需要抛出检查异常,功能同 get(),但将异常包装为 RuntimeException,在 Stream/Lambda 中用起来更优雅。
    • complete(T value):手动完成,不需要抛出检查异常。如果任务还没完,强制将结果设为 value 并唤醒所有等待者(返回 true)。
    • completeExceptionally(ex):强制让该 Future 以指定异常宣告失败。

如果你想要的是 “先定义好任务逻辑,直到被调用时才执行”的惰性机制(Lazy Execution),CompletableFuture 不具备这种特性:

  • CompletableFuture.supplyAsync(…):立即执行(Eager)。调用方法即提交线程池。
  • Mono / Flux(Spring WebFlux / Project Reactor):惰性执行(Lazy)。声明 Mono.fromSupplier(…) 时什么都不会发生,只有当调用 .subscribe() 时才会真正触发执行。
  • Java Supplier<CompletableFuture>:如果希望延迟 CompletableFuture 的执行,必须手动将其包裹在 Supplier 闭包中,在需要时再调用 .get() 触发:
1
2
3
4
5
6
7
8
9
// 此时不会执行
Supplier<CompletableFuture<String>> taskSupplier =
() -> CompletableFuture.supplyAsync(() -> {
System.out.println("task02");
return "bbb";
});

// 直到调用 get() 时才真正触发执行
CompletableFuture<String> future = taskSupplier.get();

另外,需要着重强调 supplyAsync / runAsync 和这里使用的 thenRunAsync 的区别。这两类 API 在 CompletableFuture(CF)中的生命周期触发机制完全不同:

  • 根任务 / 发起 API:例如 CompletableFuture.runAsync(…)、CompletableFuture.supplyAsync(…),它们是Eager 立即触发的,代码行执行时,立刻打包提交给线程池跑。
  • 依赖回调 API:例如 future.thenRunAsync(…)、future.thenApplyAsync(…),它们是 Event-Driven 事件驱动触发的,必须等待它依赖的父级 future 变成 Completed(完成状态) 后,才会向线程池提交并执行!

下面的 模拟 CountDownLatch - 模拟场景 A:发令枪 的例子就充分说明了这一点。


其他进阶 API

如果你想从熟练使用跨越到精通级别,以下这 4 个维度的进阶 API 是必须补充掌握的。

第一,JDK 9+ 引入的 “超时控制” 核心 API。在 JDK 8 中,CompletableFuture 最被人吐槽的就是缺少原生的异步超时机制(只能靠 get(timeout, unit) 阻塞死等)。从 JDK 9 开始,官方补齐了两个关键方法:

  • orTimeout(timeout, unit):指定时间内若任务未完成,自动抛出 TimeoutException 触发异常链。异步接口超时兜底。结合 exceptionally 使用,超时后直接返回降级数据,彻底避免死等。
  • completeOnTimeout(value, timeout, unit):指定时间内若任务未完成,自动用指定的默认值完成(不抛异常)。比如推荐系统请求超时,直接返回默认的热门排行榜。

第二,状态查询与流控 API(防御性编程)。在复杂的异步系统中,经常需要在外部判断当前 Future 处于什么状态,或者取消任务,避免无用功。

  • isDone():是否已完成(成功、失败或被取消均返回 true)。用于非阻塞判断,避免无谓的 join() 阻塞。
  • isCompletedExceptionally():是否异常/被取消(只有以抛异常或 cancel 结束才返回 true)。用于准确区分任务是 “正常跑完” 还是 “出事了”。
  • isCancelled():是否通过 cancel() 被显式取消。判断是否是被人为中断的。
  • cancel(boolean mayInterruptIfRunning):尝试取消当前任务的执行(返回 boolean)。注意如果任务已经在线程池里跑起来了,默认它无法强制中断正在运行的线程(类似 mayInterruptIfRunning 作用有限),它主要影响后续回调不再触发,并把 Future 置为 Cancelled 状态。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.concurrent.CompletableFuture;

public class FutureStatusDemo {

public static void main(String[] args) throws InterruptedException {
System.out.println("=== 场景 1:正常完成的任务 ===");
testNormalCompletion();

System.out.println("\n=== 场景 2:抛出异常的任务 ===");
testExceptionalCompletion();

System.out.println("\n=== 场景 3:显式取消 (cancel) 的任务 ===");
testCancelledCompletion();
}

// 1. 测试正常完成
private static void testNormalCompletion() {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "成功结果");

// 等待任务跑完
future.join();

printStatus("正常完成", future);
}

// 2. 测试抛出异常完成
private static void testExceptionalCompletion() {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("数据库连接超时!");
});

// 捕获 join 抛出的 CompletionException,仅为了让主线程继续运行
try {
future.join();
} catch (Exception ignored) {}

printStatus("异常结束", future);
}

// 3. 测试显式 cancel 取消
private static void testCancelledCompletion() throws InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
// 模拟一个较长的任务
Thread.sleep(1000);
} catch (InterruptedException e) {
// 注意:CF 的 cancel(true) 无法直接中断 sleep 中的线程
}
return "延迟结果";
});

// 立即发起取消动作
boolean cancelSuccess = future.cancel(true);
System.out.println("cancel(true) 执行结果: " + cancelSuccess);

// 稍微等待,让后台逻辑跑完
Thread.sleep(1200);

printStatus("显式取消", future);
}

// 统一打印 3 个状态 API 的返回值
private static void printStatus(String tag, CompletableFuture<?> future) {
System.out.println("[" + tag + "] isDone() : " + future.isDone());
System.out.println("[" + tag + "] isCompletedExceptionally(): " + future.isCompletedExceptionally());
System.out.println("[" + tag + "] isCancelled() : " + future.isCancelled());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
=== 场景 1:正常完成的任务 ===
[正常完成] isDone() : true
[正常完成] isCompletedExceptionally(): false
[正常完成] isCancelled() : false

=== 场景 2:抛出异常的任务 ===
[异常结束] isDone() : true
[异常结束] isCompletedExceptionally(): true
[异常结束] isCancelled() : false

=== 场景 3:显式取消 (cancel) 的任务 ===
cancel(true) 执行结果: true
[显式取消] isDone() : true
[显式取消] isCompletedExceptionally(): true
[显式取消] isCancelled() : true

第三,结果流式提取与副作用处理(调试与监控)。当你不需要改变 Pipeline 中的数据流,只是想在“半路”做一些打印日志、监控打点、或者判断状态的动作时。

  • whenComplete(BiConsumer action):入参为 (result, exception)。只读监听!它不会改变下一个节点拿到的结果。哪怕你在 whenComplete 里抛出了异常,或者试图返回新值,它依然会把上一步原封不动的结果传递给下游(除非 action 本身抛出了新异常)。极其适合做全局 Async 日志记录/链路追踪(TraceId)。
  • obtrudeValue(T value):强制将结果修改为 value(即使任务早已完成或失败)。极其危险/黑魔法。主要用于内部测试或极特殊的事故恢复,会无视之前的完成状态,强行覆写结果,生产环境慎用。
  • obtrudeException(Throwable ex):强制将状态修改为指定的异常。同上,强行覆写为异常。

第四,深入底层与高级扩展 API(底层适配)。当你需要将 CompletableFuture 与已有的旧代码(如旧版 Future 或第三方响应式框架)进行对接时。

  • toCompletableFuture():实现自 CompletionStage 接口,将 stage 强转/转换为真正的 CompletableFuture 实体。CompletionStage 是一个纯粹的函数式回调接口(只有 thenApply、thenAccept 等响应式方法),没有阻塞等待的 .join() / .get() 方法。调用 .toCompletableFuture() 是从抽象接口转回可调控实体对象的通用机制。
  • minimalCompletionStage():返回一个新的 CompletionStage,该对象禁用了所有的 complete() / obtrude() 手动修改状态的方法(调用会抛 UnsupportedOperationException)。专门用于 API 防御性设计。如果你在写公共组件/SDK,需要把内部的 CompletableFuture 返回给第三方调用者,使用此方法转换后,能阻止使用者通过 complete()、obtrudeValue() 等手段在外部恶意或无意地篡改你内部任务的状态。
  • defaultExecutor() (JDK 9+):用于获取当前 CF 对象在没有显式指定 Executor 时所使用的默认线程池(通常是 ForkJoinPool.commonPool())。主要方便自定义框架在重写或扩展 CF 时获取上下文默认线程池,无需硬编码全局变量。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;

public class StageApiDemo {

public static void main(String[] args) {
System.out.println("=== 1. minimalCompletionStage() 安全防护测试 ===");
testMinimalCompletionStage();

System.out.println("\n=== 2. toCompletableFuture() 类型转换测试 ===");
testToCompletableFuture();

System.out.println("\n=== 3. defaultExecutor() 默认线程池获取测试 ===");
testDefaultExecutor();
}

// 1. 模拟安全暴露场景:防外部恶意修改状态
private static void testMinimalCompletionStage() {
CompletableFuture<String> sourceFuture = new CompletableFuture<>();

// 生成安全视图:仅暴露只读/回调能力的 CompletionStage
CompletionStage<String> safeStage = sourceFuture.minimalCompletionStage();
// 给外部插件/回调方法挂载逻辑(正常消费不受影响)
safeStage.thenAccept(res -> System.out.println("外部接收到数据: " + res));

// 尝试强行将 CompletionStage 转回 CompletableFuture 并手动 complete()
// toCompletableFuture() 返回的是基于 safeStage 产生的全新独立分支。
// 数据流动是 单向的:只有 sourceFuture 完成,才会驱动 safeStage,进而驱动 tamperedFuture。
// 底层实际上是向 safeStage(本质指向 sourceFuture)注册了一个下游监听者。
// sourceFuture 算完了 -> 通知 safeStage -> 通知 tamperedFuture 填充结果。
// 如果外部在 sourceFuture 还没算完时,主动调了 tamperedFuture.complete("篡改"),这相当于下游节点单方面切断了和上游的联系。tamperedFuture 自己强行标记为完成。
// 当未来某个时刻 sourceFuture 真正算完并向下游推送数据时,tamperedFuture 检测到自己已经被填充过了,就会直接丢弃上游推过来的真实数据。
CompletableFuture<String> tamperedFuture = safeStage.toCompletableFuture();
tamperedFuture.complete("外部篡改的数据"); // 只能改变 tamperedFuture 的状态,而不能逆向改变 safeStage 的状态!

// 源 Future 依然正常运转
sourceFuture.complete("内部官方真实数据");
}

// 2. 模拟面向 CompletionStage 接口编程时的降级/提取结果场景
private static void testToCompletableFuture() {
// 假设某个三方 SDK 接口只返回了轻量级的 CompletionStage
CompletionStage<String> stage = CompletableFuture.supplyAsync(() -> "SDK 返回的异步数据");

// CompletionStage 接口没有 join() / get() 方法
// 通过 toCompletableFuture() 转换回实体的 CompletableFuture 即可调用 join()
CompletableFuture<String> future = stage.toCompletableFuture();
String result = future.join();

System.out.println("通过 toCompletableFuture().join() 成功拿到数据: " + result);
}

// 3. 探查底层默认线程池(JDK 9+)
private static void testDefaultExecutor() {
CompletableFuture<Void> future = new CompletableFuture<>();

// 获取底层默认使用的 Executor 实例
Executor executor = future.defaultExecutor();

System.out.println("当前 CompletableFuture 默认使用的线程池类: " + executor.getClass().getName());
System.out.println("默认线程池对象: " + executor);
}
}
1
2
3
4
5
6
7
8
9
=== 1. minimalCompletionStage() 安全防护测试 ===
外部接收到数据: 内部官方真实数据

=== 2. toCompletableFuture() 类型转换测试 ===
通过 toCompletableFuture().join() 成功拿到数据: SDK 返回的异步数据

=== 3. defaultExecutor() 默认线程池获取测试 ===
当前 CompletableFuture 默认使用的线程池类: java.util.concurrent.ForkJoinPool
默认线程池对象: java.util.concurrent.ForkJoinPool@2b193f2d[Running, parallelism = 7, size = 1, active = 0, running = 0, steals = 1, tasks = 0, submissions = 0]
1
2
3
4
5
6
7
8
9
10
11
12
13
【源头】                      【只读防爆墙】                 【外部派生节点】
sourceFuture ─────────► safeStage ─────────► tamperedFuture
(持有真实逻辑) (仅暴露回调) (toCompletableFuture)
│ │ │
│ │ │
可以触发 ───────────────► 可以触发 ───────────────► 可以触发
safeStage thenAccept tamperedFuture
▲ ▲ │
│ │ │
└─────────────────────────┴───────────────────────────X (反向被阻断!主动 complete 只能影响自己)

【注意】tamperedFuture 订阅的是 safeStage 本身的值,而不是 thenApply 返回的新 Stage,
它只关注 sourceFuture 的 thenApply 等操作,而不关心 safeStage 类型操作。

结合上一轮的核心 API,真正工业级的 CompletableFuture 管道逻辑通常是这样构建的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 1. 指定自定义线程池启动任务
CompletableFuture.supplyAsync(() -> fetchUserData(userId), customExecutor)
// 2. [进阶] 设置 1.5 秒超时控制,超时自动抛 TimeoutException
.orTimeout(1500, TimeUnit.MILLISECONDS)
// 3. 核心链式转换
.thenApply(this::parseUserRole)
// 4. [进阶] 纯监听打点 (不破坏数据流),记录日志/统计耗时
.whenComplete((result, ex) -> {
if (ex != null) log.warn("用户数据读取异常", ex);
else log.info("用户权限加载成功: {}", result);
})
// 5. 核心异常降级 (捕获包括 TimeoutException 在内的所有异常)
.exceptionally(ex -> UserRole.GUEST) // 降级为游客权限
// 6. [进阶] 安全导出为只读 Stage 暴露给上层服务
.minimalCompletionStage();

通过这一套 supplyAsync (启动) + orTimeout (超时防爆) + whenComplete (链路监控) + exceptionally (兜底降级) 的组合拳,你的异步代码不仅效率极高,而且具备极强的健壮性与可监控性。


五类核心 API 的简单案例

为了将 CompletableFuture 的五类核心 API 系统性地串联起来,下面设计了一个完整案例:电商商品详情页数据聚合系统。通过这个案例,我们将单任务启动、串行转换、双任务并行/竞速、多任务批量控制、异常降级以及结果手动操控整合在一套流畅的代码中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import java.util.concurrent.*;

public class CompletableFutureTest {

private static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException ignored) {}
}

private static String threadName() {
return Thread.currentThread().getName();
}

public static void main(String[] args) {
System.out.println("========== 1. 任务创建与启动 API ==========");
// 1.1 supplyAsync: 异步获取用户优惠券折扣(带返回值)
CompletableFuture<Double> couponFuture = CompletableFuture.supplyAsync(() -> {
sleep(200);
System.out.println("-> [线程 " + threadName() + "] 异步查询用户优惠券完成");
return 0.85; // 85折
});
// 1.2 runAsync: 异步打印用户浏览日志(无返回值)
CompletableFuture<Void> logFuture = CompletableFuture.runAsync(() -> {
sleep(100);
System.out.println("-> [线程 " + threadName() + "] 异步记录浏览日志完成");
});
// 1.3 completedFuture: 已知兜底汇率直接封装
CompletableFuture<Double> exchangeRateFuture = CompletableFuture.completedFuture(7.2);


System.out.println("\n========== 2. 单任务依赖转换 API(串行链式调用)==========");
// 2.1 thenApply: 数据转换 (商品裸价 1000 元 -> 85折后价格 850 元)
CompletableFuture<Double> discountedPriceFuture = couponFuture.thenApply(discount -> {
System.out.println("-> [thenApply] 计算折扣后价格");
return 1000.0 * discount;
});
// 2.2 thenAccept: 消费结果 (打印日志)
discountedPriceFuture.thenAccept(price ->
System.out.println("-> [thenAccept] 消费折扣价: " + price)
);
// 2.3 thenRun: 纯通知收尾
discountedPriceFuture.thenRun(() ->
System.out.println("-> [thenRun] 单任务链式处理完毕")
);


System.out.println("\n========== 3. 多任务组合与编排 API ==========");
// ----------------- 3.1 一对一组合(thenCompose 扁平化) -----------------
CompletableFuture<String> orderFuture = CompletableFuture.supplyAsync(() -> "USER_10086")
.thenCompose(userId -> CompletableFuture.supplyAsync(() -> {
sleep(150);
return "用户[" + userId + "]的最新订单信息";
}));
// ----------------- 3.2 双任务并行聚合(AND 关系) -----------------
// 模拟:并发查“基本信息”和“库存”,合并为商品详情
CompletableFuture<String> baseInfoFuture = CompletableFuture.supplyAsync(() -> "iPhone 16");
CompletableFuture<Integer> stockFuture = CompletableFuture.supplyAsync(() -> 99);
CompletableFuture<String> detailFuture = baseInfoFuture.thenCombine(stockFuture,
(infoString, stockInteger) -> infoString + " | 库存: " + stockInteger
);

// thenAcceptBoth: 合并消费无返回
baseInfoFuture.thenAcceptBoth(stockFuture, (infoString, stockInteger) ->
System.out.println("-> [thenAcceptBoth] 聚合预览: " + infoString + " (存量:" + stockInteger + ")")
);

// runAfterBoth: 两者完成后执行收尾动作
baseInfoFuture.runAfterBoth(stockFuture, () ->
System.out.println("-> [runAfterBoth] 基本信息与库存就绪!")
);

// ----------------- 3.3 双任务竞速(OR 关系) -----------------
// 模拟:从两个镜像节点并发拉取评价数据,谁快用谁
CompletableFuture<String> cdnNodeA = CompletableFuture.supplyAsync(() -> { sleep(300); return "节点 A 评价"; });
CompletableFuture<String> cdnNodeB = CompletableFuture.supplyAsync(() -> { sleep(100); return "节点 B 评价"; });

// applyToEither: 谁快就转换谁
CompletableFuture<String> fastestReview = cdnNodeA.applyToEither(cdnNodeB, resultString -> "【最快响应】" + resultString);
// acceptEither: 谁快就直接消费
cdnNodeA.acceptEither(cdnNodeB, resultString -> System.out.println("-> [acceptEither] 率先拿到: " + resultString));
// runAfterEither: 任意一个完即触发
cdnNodeA.runAfterEither(cdnNodeB, () -> System.out.println("-> [runAfterEither] 已有节点响应"));

// ----------------- 3.4 多任务批量控制(N 个任务) -----------------
// allOf: 等待商品详情、折扣价、订单三个异步任务全部完成
CompletableFuture<Void> allTasks = CompletableFuture.allOf(detailFuture, discountedPriceFuture, orderFuture);
allTasks.thenRun(() -> System.out.println("-> [allOf] 页面所需要的所有依赖任务全部加载完毕!"));

// anyOf: 镜像节点快速响应
CompletableFuture<Object> anyTask = CompletableFuture.anyOf(cdnNodeA, cdnNodeB);
anyTask.thenAccept(result -> System.out.println("-> [anyOf] 收到首个响应对象: " + result));


System.out.println("\n========== 4. 异常处理 API ==========");
// 模拟一个必然抛出异常的异步服务(推荐商品服务)
CompletableFuture<String> recommendFuture = CompletableFuture.supplyAsync(() -> {
if (true) {
throw new RuntimeException("推荐系统服务宕机!");
}
return "推荐商品列表";
});

// 4.1 exceptionally: 捕获异常并降级
CompletableFuture<String> fallbackFuture = recommendFuture.exceptionally(ex -> {
System.out.println("-> [exceptionally] 捕获异常: " + ex.getMessage() + ",返回热销托底数据");
return "托底默认热门商品";
});

// 4.2 handle: 无论成功还是失败,均可获取 (result, ex) 进行加工转换
CompletableFuture<String> handledFuture = recommendFuture.handle((res, ex) -> {
if (ex != null) {
return "【Handle 降级处理】空推荐列表";
}
return res;
});

// 4.3 whenComplete: 无论成功还是失败均触发(纯观察/记录日志)
recommendFuture.whenComplete((res, ex) -> {
if (ex != null) {
System.out.println("-> [whenComplete] 监控告警:推荐服务调用异常!");
}
});


System.out.println("\n========== 5. 结果获取与手动操控 API ==========");
// 5.1 join(): 阻塞获取结果,异常时包装为 RuntimeException(适合 Lambda)
String finalDetail = detailFuture.join();
System.out.println("-> [join] 最终聚合商品信息: " + finalDetail);

// 5.2 getNow(): 非阻塞获取,若任务未完成,返回传入的默认兜底值
String reviewRightNow = cdnNodeA.getNow("暂无评价(超时兜底)");
System.out.println("-> [getNow] 尝试直接提取节点 A 数据: " + reviewRightNow);

// 5.3 get(timeout, unit): 带超时的阻塞获取
try {
String orderResult = orderFuture.get(1, TimeUnit.SECONDS);
System.out.println("-> [get(timeout)] 获取订单结果: " + orderResult);
} catch (TimeoutException e) {
System.out.println("-> [get(timeout)] 获取订单超时");
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}

// 5.4 complete() / completeExceptionally(): 手动操控 Future 状态
CompletableFuture<String> manualFuture = new CompletableFuture<>();

// 启动一个后台线程,如果 500ms 后没完成,主线程手动强行给它设置结果
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(() -> {
boolean success = manualFuture.complete("【外部强行注入的第三方缓存结果】");
System.out.println("-> [complete] 手动完成结果设置: " + success);
}, 100, TimeUnit.MILLISECONDS);
System.out.println("-> [join 手动操控结果]: " + manualFuture.join());

// 保持主线程短暂挂起,等待所有异步线程日志打印完毕
sleep(500);
executor.shutdown();
}
}

其他具体案例,也可以参考 CompletableFuture 一些案例 。


模拟或包装常用组件

CompletableFuture(简称 CF)的本质是一个 “可手动完成的异步结果容器 + 声明式状态回调驱动器”。依靠它的 complete()、allOf()、anyOf() 以及链式回调,不仅能模拟常见的并发组件,而且在许多场景下比原生的 JUC 工具更优雅——因为原生工具是阻塞线程(Blocking)的,而 CF 是响应式/非阻塞(Non-blocking)的。


模拟 CountDownLatch

原生的 CountDownLatch 需要线程调用 await() 死等。而 CF 模拟它不仅不需要阻塞线程,还能直接拿到所有子任务的结果。

模拟场景 A:发令枪。

这里需要澄清一下:CompletableFuture 的模拟,并不是严格的同时运行,甚至在微秒级/纳秒级时间线上,它们是有明确先后顺序的。这里有三个层面的“非严格同时”:

  • 任务提交的微观先后(Push 延迟):complete() 遍历链表提交任务是一个 for 循环(或 while 循环)。任务 1 被提交到线程池的队列中;几百纳秒后,任务 2 被提交;再过几百纳秒,任务 3 被提交。任务进入线程池队列的时间本身就有微小的先后顺序。
  • 线程池调度的微观先后(Worker 抢占):ForkJoinPool 的 Worker 线程从队列中 Take/Steal 任务并开始执行,涉及到 CPU 锁竞争和上下文唤醒。谁先抢到 CPU 时间片,谁就先输出。
  • 硬件 CPU 核心数的物理限制:如果你的 CPU 只有 2 个物理核心,而你提交了 3 个任务,在物理上最多只能有两个任务在同一时刻并行(Parallel),第三个任务必须等待前两个任务之一让出 CPU。

所以,如果你追求“纯异步、高吞吐、极致节省线程资源”,使用 CompletableFuture 这种非阻塞回调模式。这是响应式/网关层最推崇的写法(发令前不需要创建 1000 个线程等待,只有发令后才根据需要向线程池投递 1000 个任务)。如果你需要“控制已有线程的硬同步”,例如压测工具(要求 100 个已经准备就绪的 HTTP 请求线程在极短时间内冲击服务器),使用 CountDownLatch 或 CyclicBarrier 更合适,因为线程已经在 await() 处就绪,唤醒延迟相对更纯粹。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(String[] args) throws InterruptedException {
// 1. 创建一个未完成的“发令枪”
CompletableFuture<Void> startGun = new CompletableFuture<>();

// 2. 多个子线程挂载在发令枪后面,等待发令
for (int i = 0; i < 3; i++) {
startGun.thenRunAsync(() -> System.out.println(new Date() + " " + Thread.currentThread().getName() + " 听到枪声,开跑!"));
}

// 3. 主线程扣动扳机(发令)
Thread.sleep(1000);
System.out.println("发令枪响!");
startGun.complete(null); // 一旦 complete,挂载的所有异步任务瞬间并发响应!
Thread.sleep(10000); // ForkJoinPool.commonPool() 默认是守护线程池(Daemon Pool)。为了防止main线程结束后 startGun 的所有任务停止,这里多睡几秒。
}
1
2
3
4
发令枪响!
ForkJoinPool.commonPool-worker-1 听到枪声,开跑!
ForkJoinPool.commonPool-worker-2 听到枪声,开跑!
ForkJoinPool.commonPool-worker-3 听到枪声,开跑!

模拟场景 B:主线程等多个子任务集齐

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) throws InterruptedException {
CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> doWork("Task1"));
CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> doWork("Task2"));
CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> doWork("Task3"));

// 相当于 latch.await(),但它是【非阻塞】的!
CompletableFuture<Void> allLatch = CompletableFuture.allOf(task1, task2, task3);

// 集齐后自动触发后续动作
allLatch.thenRun(() -> System.out.println("所有子任务已集齐,开始汇总数据!"));
}


模拟 Semaphore

Semaphore 通常可以充当信号量 或 限流器,用于控制同时访问某个资源的线程数量。下面是简单的模拟代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncSemaphoreTest {

public static void main(String[] args) throws InterruptedException {
// 实例化一个并发度限制为 2 的异步信号量
AsyncSemaphore semaphore = new AsyncSemaphore(2);
ExecutorService executor = Executors.newFixedThreadPool(4);

// 模拟 5 个异步任务同时争抢 2 个许可
for (int i = 1; i <= 5; i++) {
final int taskId = i;

// 1. 异步申请许可(非阻塞!)
semaphore.acquire().thenAcceptAsync(v -> {
// 2. 拿到许可后执行受保护的核心业务
System.out.println("-> 任务 " + taskId + " 拿到许可,开始处理执行...");
randomSleep();
System.out.println("<- 任务 " + taskId + " 处理完毕,释放许可。");
}, executor).whenComplete((voidResult,ex) -> {
// 3. 业务执行完毕后,必须释放许可
semaphore.release();
});
}

Thread.sleep(10000); // 等待所有任务完成
executor.shutdown();
}

private static void randomSleep() {
try {
Thread.sleep((long) (Math.random() * 2000 + 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}

/**
* 基于 CompletableFuture 实现的非阻塞 Semaphore
*/
static class AsyncSemaphore {
private int permits;
private final Queue<CompletableFuture<Void>> waitQueue = new LinkedList<>();

public AsyncSemaphore(int permits) {
if (permits <= 0) {
throw new IllegalArgumentException("Permits must be > 0");
}
this.permits = permits;
}

/**
* 异步获取许可(非阻塞)
* @return 当获得许可时完成的 CompletableFuture
*/
public synchronized CompletableFuture<Void> acquire() {
if (permits > 0) {
permits--;
// 有剩余许可,直接返回已完成的 Future
return CompletableFuture.completedFuture(null);
} else {
// 许可不足,创建一个占位的 Future 入队,等待 release 唤醒
CompletableFuture<Void> future = new CompletableFuture<>();
waitQueue.add(future);
return future;
}
}

/**
* 释放许可
*/
public synchronized void release() {
CompletableFuture<Void> nextTask = waitQueue.poll();
if (nextTask != null) {
// 队列中有等待的任务,直接把许可交给它(不增加 permits 计数)
nextTask.complete(null);
} else {
// 没有等待者,归还许可
permits++;
}
}
}
}
1
2
3
4
5
6
7
8
9
10
-> 任务 1 拿到许可,开始处理执行...
-> 任务 2 拿到许可,开始处理执行...
<- 任务 2 处理完毕,释放许可。
-> 任务 3 拿到许可,开始处理执行...
<- 任务 1 处理完毕,释放许可。
-> 任务 4 拿到许可,开始处理执行...
<- 任务 3 处理完毕,释放许可。
-> 任务 5 拿到许可,开始处理执行...
<- 任务 4 处理完毕,释放许可。
<- 任务 5 处理完毕,释放许可。


模拟 CyclicBarrier

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;

public class CompletableFutureTest {

public static void main(String[] args) {
int players = 3;
// 定义栅栏:3个人到齐后,由最后一个人顺便执行“宣布结果”的任务
CfCyclicBarrier barrier = new CfCyclicBarrier(players, x -> {
System.out.println("--- 所有人都到齐了,关卡开启! ---");
});

for (int i = 0; i < players; i++) {
final int id = i;
new Thread(() -> {
try {
System.out.println("玩家 " + id + " 正在加载地图...");
Thread.sleep((long) (Math.random() * 2000));

System.out.println("玩家 " + id + " 已到达第一关栅栏。");
// 关键修复:必须调用 .join() 真正阻塞当前线程!
barrier.await().join();

System.out.println("玩家 " + id + " 开始打怪...");
Thread.sleep((long) (Math.random() * 2000));

System.out.println("玩家 " + id + " 已到达第二关栅栏。");
// 循环使用:再次等待
barrier.await().join();

System.out.println("玩家 " + id + " 顺利通关!");
} catch (Exception e) {
e.printStackTrace();
}
}, "Player-" + id).start();
}
}

static class CfCyclicBarrier {
private final int parties;
private List<CompletableFuture<Void>> currentBatch = new ArrayList<>();
private final Consumer<?> consumer;

public CfCyclicBarrier(int parties, Consumer<?> consumer) {
this.parties = parties;
this.consumer = consumer;
}

// 线程到达屏障点,返回一个代表“冲破屏障”的 Future
public synchronized CompletableFuture<Void> await() {
CompletableFuture<Void> future = new CompletableFuture<>();
currentBatch.add(future);

// 如果刚好凑齐了指定人数
if (currentBatch.size() == parties) {
// 1. 触发屏障开启回调
if (consumer != null) {
consumer.accept(null);
}

// 2. 暂存当前这批 Future,并重置 currentBatch 为下一轮做准备
List<CompletableFuture<Void>> batchToComplete = currentBatch;
currentBatch = new ArrayList<>();

// 3. 手动唤醒本轮所有等待的线程
batchToComplete.forEach(cf -> cf.complete(null));
}
return future;
}
}
}


模拟 Exchanger

这个 AsyncExchanger 的核心作用是在两个异步任务/线程之间“对调数据”,而且全程非阻塞。它的设计灵感来源于 JDK 的 java.util.concurrent.Exchanger,但传统 Exchanger 是同步阻塞的(线程会卡住等对方),而这个实现返回的是 CompletableFuture,使用者不需要阻塞挂起线程,只需通过链式回调(如 .thenAccept() 或 .thenApply())来响应对方送过来的数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.concurrent.CompletableFuture;

public class CompletableFutureTest {

public static void main(String[] args) throws InterruptedException {
AsyncExchanger<String> tradeBox = new AsyncExchanger<>();

// ================= 玩家 A 的异步逻辑 =================
CompletableFuture.runAsync(() -> {
simulateWork("玩家 A(战士)正在整理背包...", 1000);

String itemFromA = "法术杖 +5";
System.out.println("玩家 A 把 [" + itemFromA + "] 放入交易框,等待对方...");

// A 放入物品,拿到代表“B 物品”的 Future,并挂接非阻塞回调
tradeBox.exchangeA(itemFromA)
.thenAccept(itemFromB -> {
System.out.println(">>> 交易成功!玩家 A 拿到了对方交换来的: [" + itemFromB + "]");
});
});

// ================= 玩家 B 的异步逻辑 =================
CompletableFuture.runAsync(() -> {
simulateWork("玩家 B(法师)正在打怪路上...", 2500); // B 动作慢一点

String itemFromB = "屠龙刀 +9";
System.out.println("玩家 B 把 [" + itemFromB + "] 放入交易框,等待对方...");

// B 放入物品,拿到代表“A 物品”的 Future,并挂接非阻塞回调
tradeBox.exchangeB(itemFromB)
.thenAccept(itemFromA -> {
System.out.println(">>> 交易成功!玩家 B 拿到了对方交换来的: [" + itemFromA + "]");
});
});

// 主线程等待一会儿,防止 JVM 退出(因为 runAsync 默认用的是守护线程)
Thread.sleep(4000);
}

private static void simulateWork(String log, long ms) {
System.out.println(log);
try {
Thread.sleep(ms);
} catch (InterruptedException ignored) {}
}

static public class AsyncExchanger<T> {
private final CompletableFuture<T> slotA = new CompletableFuture<>();
private final CompletableFuture<T> slotB = new CompletableFuture<>();

// 线程 A 调用:放入 A 的数据,等待并获取 B 的数据
public CompletableFuture<T> exchangeA(T itemFromA) {
slotA.complete(itemFromA); // 把自己的数据放入 A 槽
return slotB; // 返回代表 B 槽数据的 Future
}

// 线程 B 调用:放入 B 的数据,等待并获取 A 的数据
public CompletableFuture<T> exchangeB(T itemFromB) {
slotB.complete(itemFromB); // 把自己的数据放入 B 槽
return slotA; // 返回代表 A 槽数据的 Future
}
}
}
1
2
3
4
5
6
玩家 A(战士)正在整理背包...
玩家 B(法师)正在打怪路上...
玩家 A 把 [法术杖 +5] 放入交易框,等待对方...
玩家 B 把 [屠龙刀 +9] 放入交易框,等待对方...
>>> 交易成功!玩家 A 拿到了对方交换来的: [屠龙刀 +9]
>>> 交易成功!玩家 B 拿到了对方交换来的: [法术杖 +5]


模拟 Phaser

Phaser 是 CyclicBarrier 和 CountDownLatch 的终极结合体,支持分阶段(Phase 0 -> Phase 1 -> Phase 2…) 动态调整参与者的协调。在 CF 的世界里,分阶段任务本质上就是“链式调用(Pipeline)”!不需要专门维护 Phase 计数器,直接用 thenCompose / thenCombine 将阶段串起来即可。

1
2
3
4
5
6
7
8
9
10
阶段 0: [ TaskA-Phase0 ]   [ TaskB-Phase0 ]
\ /
\ /
CompletableFuture.allOf() <--- 阶段 0 栅栏
|
v
阶段 1: [ TaskA-Phase1 ] [ TaskB-Phase1 ]
\ /
\ /
CompletableFuture.allOf() <--- 阶段 1 栅栏

模拟代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) throws InterruptedException {
// 第一阶段:并发执行 A0 和 B0
CompletableFuture<String> a0 = CompletableFuture.supplyAsync(() -> "A-Phase0");
CompletableFuture<String> b0 = CompletableFuture.supplyAsync(() -> "B-Phase0");

// 阶段 0 屏障:集齐第一阶段结果
CompletableFuture<Void> phase0Barrier = CompletableFuture.allOf(a0, b0);

// 进入第二阶段:阶段 0 完毕后,自动触发 A1 和 B1
CompletableFuture<Void> phase1 = phase0Barrier.thenRunAsync(() -> {
System.out.println("Phase 0 全部完成,开始 Phase 1!");
}).thenCompose(voidResult -> {
CompletableFuture<String> a1 = CompletableFuture.supplyAsync(() -> "A-Phase1");
CompletableFuture<String> b1 = CompletableFuture.supplyAsync(() -> "B-Phase1");
return CompletableFuture.allOf(a1, b1); // 阶段 1 屏障
}).thenRunAsync(() -> {
System.out.println("Phase 1 全部完成,Done!");
});

// 主线程等待一会儿,防止 JVM 退出(因为 runAsync 默认用的是守护线程)
Thread.sleep(4000);
}


阶段总结

原生的 JUC 工具是“以 Thread 为中心”的,通过挂起/唤醒线程(阻塞)来实现协调;而 CompletableFuture 是 “以 Data/Event 为中心” 的,通过数据流到达(事件触发)驱动后续逻辑,是向响应式编程(Reactive Programming) 演进的核心思想。

并发组件 原生 JUC 工具特点 CompletableFuture 模拟的优势
CountDownLatch 线程必须 .await() 阻塞等待,无法传递结果。 非阻塞回调(allOf),且能方便地组合各个子任务的结果。
Semaphore 基于 AQS 阻塞排队线程。 可结合线程池与响应式队列实现真正的非阻塞限流。
CyclicBarrier 固定的线程数同步死等,抛出检查异常繁琐。 同样非阻塞,且与链式 CallBack 无缝集成。
Exchanger 只能两个阻塞线程同步交接。 支持异步数据交换,数据准备好后自动解包回调。
Phaser 概念极其复杂,API 学习成本高。 用 CF 链式依赖天然表达“阶段性”,代码极其直观。

但是在效率上 CompletableFuture 依然稍逊一筹。CompletableFuture 模拟的异步 Semaphore 虽然非阻塞(不挂起 Thread),但在吞吐量、CPU 内存开销、GC 压力等绝对性能指标上,依然比不过基于 AQS(AbstractQueuedSynchronizer)的原生 Semaphore。

性能维度 JDK 原生 Semaphore (AQS) CompletableFuture 模拟 (无锁/锁) 胜者
内存与 GC 压力 极低。内部仅维护 AQS 链表节点(Node),无频繁对象创建。 较高。每次 acquire() 竞争失败都会 new CompletableFuture() 和入队节点,高并发下引发频繁 GC。 JDK 原生
CPU 占用 (无竞争/低竞争) 极低。纯 CAS 更新一个 volatile state 计数器,无锁重路径。 中等。即便拿到许可,也要封装/返回 Future 对象,存在对象创建开销。 JDK 原生
CPU 占用 (高竞争/阻塞等待) 较好。争抢失败后线程通过 LockSupport.park() 被挂起,彻底释放 CPU 资源。 较差。如果是无锁 CAS 实现,高并发下大量线程在 while(true) 循环里自旋争抢,会导致 CPU 飙升。 JDK 原生
线程上下文切换 有开销。许可不足时会触发操作系统 Thread 上下文切换。 零切换。纯内存状态挂接,不挂起 Thread,适合 Reactor / Netty 线程模型。 CompletableFuture


实现异步 Semaphore

标准异步 Semaphore

在响应式框架(如 Resilience4j、Netty、Project Reactor)中,标准的异步 Semaphore 实现绝不是简单地加锁,也不是无限自旋 CAS,而是采用 “轻量 CAS 抢占 + 无锁无界队列(MPSC/MPMC)+ 线程安全队列清理” 的经典范式。为了避免高并发下的锁竞争与 GC 污染,标准的实现遵循以下三个核心原则:

  • 无锁 Fast-Path(快路径):没有竞争时,纯 CAS 修改计数器,零队列开销。
  • 延迟创建(Lazy Allocation):只有许可不足排队时,才创建 CompletableFuture。
  • 取消安全性(Cancellation-Safe):超时或取消(cancel())时,能自动从队列清理废弃节点,防止许可泄露。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
* 标准异步非阻塞 Semaphore (AsyncSemaphore)
*/
public class StandardAsyncSemaphore {

private final AtomicInteger permits;
private final Queue<CompletableFuture<Void>> waitQueue = new ConcurrentLinkedQueue<>();

public StandardAsyncSemaphore(int initialPermits) {
if (initialPermits <= 0) {
throw new IllegalArgumentException("Initial permits must be > 0");
}
this.permits = new AtomicInteger(initialPermits);
}

/**
* 异步获取许可(非阻塞)
*/
public CompletableFuture<Void> acquire() {
while (true) {
int current = permits.get();

// 1. Fast-Path: 还有许可,直接 CAS 扣减(最频繁发生的场景)
if (current > 0) {
if (permits.compareAndSet(current, current - 1)) {
// 零对象创建开销,直接返回全局单例 completedFuture
return CompletableFuture.completedFuture(null);
}
// CAS 失败(存在线程竞争),重试循环
} else {
// 2. Slow-Path: 许可不足,延迟创建 Future 并入队
CompletableFuture<Void> future = new CompletableFuture<>();

// 监听取消事件:如果上层超时/取消,自动将此节点从队列移除,防止内存泄露与无效唤醒
future.whenComplete((voidResult, ex) -> {
if (future.isCancelled()) {
waitQueue.remove(future);
}
});
waitQueue.add(future);

// 3. Double-Check(二次检查):防止在 add 瞬间恰好有 release() 发生而导致的挂起(Lost Wakeup)
if (permits.get() > 0 && waitQueue.remove(future)) {
// 成功抢回节点,说明有新许可释放,重新回到循环去抢 CAS
continue;
}
return future;
}
}
}

/**
* 释放许可
*/
public void release() {
while (true) {
CompletableFuture<Void> nextTask = waitQueue.poll();

if (nextTask != null) {
// 尝试唤醒队列头的 Future。
// 如果 complete(null) 返回 true,说明成功唤醒了等待者(将许可直接转移给它);
// 如果返回 false,说明这个 Future 已经被取消/超时了,继续 poll 下一个!
if (nextTask.complete(null)) {
return;
}
} else {
// 队列为空,归还许可
permits.incrementAndGet();

// 二次检查:如果在 incrementAndGet 完成后,刚好有新任务入队
if (!waitQueue.isEmpty() && permits.get() > 0) {
// 尝试把加上的许可扣回来,继续进入循环唤醒等待队列里的任务
if (permits.compareAndSet(permits.get(), permits.get() - 1)) {
continue;
}
}
break;
}
}
}

public int getAvailablePermits() {
return Math.max(0, permits.get());
}
}


为什么使用它?

要理解为什么标准异步 Semaphore “更好”,我们需要从 底层 CPU 调度、内存开销 和 架构设计 三个维度彻底拆解:

  • 彻底解决 EventLoop / 响应式线程池的“卡死”问题:

    • 传统 JDK Semaphore 的致命缺陷:原生 semaphore.acquire() 依赖 AQS 的 LockSupport.park(),它会直接把系统 Thread 挂起并剥夺 CPU 时间片。在 Netty、Vert.x 或 Spring WebFlux 等响应式架构中,核心 EventLoop 线程数通常只有 8~16 个。一旦在 EventLoop 线程里调用了原生 acquire() 且许可不足,该核心线程就会被强行挂起。 只要有 16 个请求卡住,整个服务器的成千上万个 API 将全部瘫痪。
    • 异步 Semaphore 的优势:异步 Semaphore 的 acquire() 是纯内存计算。许可不足时,它仅仅是把回调函数挂在 CompletableFuture 上,线程立刻释放去处理其他网络 IO。当 release() 被调用时,由释放者线程(或线程池)顺手触发回调。
    • 本质区别:传统 Semaphore 保护资源,牺牲线程;异步 Semaphore 既保护资源,又保住线程。
  • Fast-Path(快路径)零对象分配,GC 极度友好

    • 在绝大多数正常运行的系统里,限流/并发控制组件在 80%~90% 的时间里都是有剩余许可的(未达到上限)。

    • 传统粗暴实现:每次 acquire() 都 new CompletableFuture(),引发大量 Young GC。

    • 标准代码的优化:

      1
      2
      3
      4
      5
      // 在许可充足时,只执行一次 CPU 的 CAS 指令,直接返回全局共享的单例 Future。
      //没有产生任何 Heap 内存分配,GC 压力直接骤降为 0!
      if (permits.compareAndSet(current, current - 1)) {
      return CompletableFuture.completedFuture(null); // 返回 JVM 内部单例
      }
  • 无锁 CAS + 双重检查(Double-Check),吞吐量远超 synchronized

    • synchronized 会引发 Monitor 锁膨胀、重量级锁竞争和上下文切换。
    • 本实现采用 AtomicInteger + ConcurrentLinkedQueue 的组合,利用 CPU 原生指令 CMPXCHG(Compare and Swap)进行无锁操作。CPU 无需进行线程上下文切换,指令执行仅需数个 CPU 时钟周期。通过“入队后二次检查(Double-Check)”,消除了线程 A 刚入队、线程 B 恰好释放许可导致的“永久挂起/死锁”漏洞。
  • 完整的 Cancellation-Safe(取消安全性)

    • 在真实业务中,异步任务经常会设置超时(如 orTimeout(3, TimeUnit.SECONDS))。如果一个任务在队列排队时超时取消了,会发生什么?
    • 粗劣实现:release() 唤醒了一个已经被 cancel() 的 Future,许可被白白丢弃,导致后续正常排队的任务永久等不到许可(许可泄露)。
    • 标准实现:future.whenComplete 监听取消动作,被取消时主动从 waitQueue 移除节点。release() 时检查 nextTask.complete(null) 的返回值。如果返回 false(说明该 Future 已被取消),while(true) 循环会自动 poll 下一个真正有效的等待者,确保许可 100% 精确传递。


最佳实践和避坑指南

CF 的线程分配机制

理解 CF 的线程分配逻辑,是掌握线程池隔离的前提:

  • supplyAsync(supplier, executor) / runAsync(runnable, executor):
    • 明确指定传入的 executor 来运行初始异步任务。
  • 非 Async 链式 API(如 thenApply, thenAccept, thenCompose):
    • 如果前置任务尚未完成:当后置逻辑被挂载时,前置任务完成后,后置逻辑将由执行前置任务的线程顺便执行。
    • 如果前置任务已经完成:后置逻辑将由调用 thenXxx 的当前线程(通常是主线程/调用方线程)直接同步执行!
  • Async 结尾的链式 API(如 thenApplyAsync(fn, executor)):
    • 无论前置任务是否完成,都将后置逻辑作为一个全新的 Task 提交给指定的 executor 异步执行。


七大最佳实践

第一,业务隔离,拒绝 ForkJoinPool.commonPool()。

绝对不要在生产代码中使用未指定 Executor 的 CF 方法(如直接 CompletableFuture.supplyAsync(supplier))。默认的 ForkJoinPool.commonPool() 是 JVM 全局共享的守护线程池,其并行度默认为 CPU核心数 - 1。如果用它执行耗时的 IO 密集型任务(如 HTTP/RPC 请求、数据库查询),极易迅速占满全局线程池,导致应用中所有依赖 commonPool 的组件(如 Java 8 ParallelStream)全部瘫痪。最佳实践是根据业务类型建立独立的线程池,隔离故障。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 生产推荐:按业务功能区分线程池
@Configuration
public class ThreadPoolConfig {

// 针对 RPC/HTTP 调用的 IO 密集型线程池
@Bean("rpcExecutor")
public Executor rpcExecutor() {
int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;
return new ThreadPoolExecutor(
corePoolSize,
corePoolSize * 4,
60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(2000),
new NamedThreadFactory("rpc-async-pool"),
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略兜底
);
}
}

第二,IO 密集型与 CPU 密集型任务的线程池配置策略。

不同性质的任务对 CPU 和线程资源的要求截然不同:

第三,显式传递线程池到 Async 链中。

如果在链式调用中存在耗时较长的重度数据加工,必须显式传入线程池:

1
2
3
4
5
// 推荐做法:不仅 supplyAsync 指定线程池,后续耗时的 Async 加工也指定线程池
CompletableFuture.supplyAsync(() -> rpcService.getUserInfo(userId), rpcExecutor)
// 如果 renderPage 极其耗时,不要用 thenApply (防止占用 RPC 线程),改为 thenApplyAsync 投递给专门的渲染/计算线程池
.thenApplyAsync(userInfo -> renderPage(userInfo), computeExecutor)
.exceptionally(ex -> getFallbackUser());

第四,必须配置显式超时机制(Timeout)。

异步编程最怕“永久等待”。JDK 9 提供了原生的 orTimeout 与 completeOnTimeout;如果使用 JDK 8,则需要基于 ScheduledExecutorService 模拟。

1
2
3
4
5
6
7
// JDK 9+ 最佳实践
CompletableFuture.supplyAsync(() -> remoteRpcCall(), rpcExecutor)
.orTimeout(2, TimeUnit.SECONDS) // 2秒超时,抛出 TimeoutException
.exceptionally(ex -> {
log.error("RPC 调用超时或失败", ex);
return fallbackValue; // 兜底降级
});

第五,多线程上下文传递(MDC TraceId / ThreadLocal 解决)。

ThreadLocal 在跨线程(如 CF 提交任务给自定义线程池)时会丢失。如果日志需要 TraceId(MDC),或者业务依赖 ThreadLocal 上下文(如用户 Session),必须做上下文传递。可以自定义 Task 包装器(TaskDecorator),在 Spring 的 ThreadPoolTaskExecutor 中设置 setTaskDecorator(new ContextCopyingDecorator()) 即可做到全局透明传递。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ContextCopyingDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
// 1. 抓取主线程的 MDC 上下文
Map<String, String> contextMap = MDC.getCopyOfContextMap();
return () -> {
try {
// 2. 写入子线程
if (contextMap != null) {
MDC.setContextMap(contextMap);
}
runnable.run();
} finally {
// 3. 清理子线程上下文,防止内存泄露与上下文污染
MDC.clear();
}
};
}
}

第六,完善的异步异常处理机制。

在同步代码中,异常会自动向上抛出;但在 CF 异步链中,未显式捕获的异常会被“吞掉”在 Future 内部,直到你调用 .join() 或 .get() 才会抛出 CompletionException。可以在在链末端一律挂载 .exceptionally() 或 .handle(),确保异常被监控记录并提供降级兜底:

1
2
3
4
5
6
7
8
9
CompletableFuture.supplyAsync(() -> fetchData(), rpcExecutor)
.handle((result, ex) -> {
if (ex != null) {
log.error("异步获取数据异常", ex);
Metrics.counter("async.fetch.error").increment();
return getFallbackData(); // 兜底降级
}
return result;
});

第七,优雅停机(Graceful Shutdown)与资源回收。

1
2
3
4
5
6
7
8
9
10
11
12
@PreDestroy
public void shutdown() {
rpcExecutor.shutdown(); // 拒绝接收新任务,但等待已提交任务完成
try {
if (!rpcExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
rpcExecutor.shutdownNow(); // 超时后强制中断
}
} catch (InterruptedException e) {
rpcExecutor.shutdownNow();
Thread.currentThread().interrupt();
}
}


八大避坑指南

坑 1:无界队列导致 OOM (Out Of Memory)

  • 现象:使用 Executors.newFixedThreadPool(n) 时,其底层使用的是无界队列 LinkedBlockingQueue(容量为 Integer.MAX_VALUE)。当上游 QPS 突增或下游响应变慢时,任务大量堆积在队列中,导致堆内存溢出(OOM)。
  • 规避方案:严禁使用 Executors 创建预设线程池! 必须手动 new ThreadPoolExecutor 并显式指定有界队列大小。

坑 2:默认拒绝策略导致的主线程无感死卡

  • 现象:使用 ThreadPoolExecutor.AbortPolicy 拒绝策略,当线程池和队列满载时,execute() 会抛出 RejectedExecutionException。如果你使用 CompletableFuture.supplyAsync 且没有外层捕获此异常,异常会导致该 Future 永远处于 Uncompleted 状态,上层调用 .join() 的主线程将无限期死等。
  • 规避方案:
    • 使用 CallerRunsPolicy 让提交任务的调用方线程自行执行,起到自然限流/背压(Backpressure)作用。
    • 捕获 RejectedExecutionException 并手动调用 future.completeExceptionally(ex)。

坑 3:嵌套 CompletableFuture 导致线程池自我死锁

  • 现象:在同一个有限大小的线程池中,Task A 内部又提交了 Task B 到同一个线程池,并调用 taskB.join() 等待 Task B 结果。当高并发到来时,所有线程都在运行 Task A 并等待 Task B,而 Task B 在队列里排队得不到线程资源,导致全盘死锁。
  • 规避方案:
    • 禁止在异步任务内部阻塞等待同一个线程池的其他异步任务。
    • 父子任务必须进行线程池隔离(父任务用 Pool A,子任务用 Pool B)。

坑 4:在主线程或公共线程池上直接 .join() / .get() 阻塞

  • 现象:在 Tomcat/Netty 处理 HTTP 请求的主线程上大量调用 future.join(),导致响应式异步彻底退化回阻塞模型,把原本应该高并发的 API 卡死在线程等待上。
  • 规避方案:采用响应式链式回调(如 thenAccept),或者在异步管道最后统一通过非阻塞方式聚合(如 CompletableFuture.allOf)。如果必须阻塞,必须带上超时时间 future.get(3, TimeUnit.SECONDS)。

坑 5:completableFuture.cancel(true) 无法真正中断正在运行的线程

  • 现象:开发者以为调用了 future.cancel(true) 就能像 Thread.interrupt() 一样立刻终止耗时任务。但在 CF 中,cancel(true) 的参数 mayInterruptIfRunning 没有任何效果!它只是把 Future 状态标记为 Cancelled,正在线程池中跑的 Runnable 依然会继续执行直至完成。
  • 规避方案:如果需要真正终止线程,必须在任务代码内部主动定期检查 Thread.currentThread().isInterrupted(),或者结合 Future 标志位手动退出。

坑 6:ThreadLocal 变量在线程重用时发生 “数据污染”

  • 现象:在异步线程中设置了 ThreadLocal(如用户 Session),任务完成后没有在 finally 中显式 remove()。因为线程池中的线程是被复用的,后续其他请求复用了该线程,直接读取到了上一次请求残留的身份信息,造成严重的数据越权与隐私安全事故。
  • 规避方案:必须在 TaskDecorator 或 try-finally 块中显式清理 ThreadLocal/MDC 上下文。

坑 7:在高并发下滥用 .thenRun() / .thenApply() 造成栈深度过大

  • 现象:在循环或递归中不断拼接非 Async 结尾的方法(如 future = future.thenApply(…)),如果前置任务极快完成,后置任务会不断在同一个线程的栈帧中深度叠加,极端情况下可能引发 StackOverflowError。
  • 规避方案:对于过长的链式管道或循环拼接,适度使用 thenApplyAsync 拆分到线程池中重新调度,打破深度调用栈。

坑 8:直接覆盖 ForkJoinPool.commonPool() 的系统属性

  • 现象:为了解决 commonPool 线程数不够的问题,在代码里通过 System.setProperty(“java.util.concurrent.ForkJoinPool.common.parallelism”, “128”) 修改配置。
  • 规避方案:修改全局系统属性会影响 JVM 内所有第三方库(如 CompletableFuture、Parallel Stream、Jackson 等)的默认行为,影响不可控。始终坚持使用自定义线程池,不污染全局配置。

结合上述所有实践,以下提供一份可直接在生产环境落地的 CompletableFuture 模版代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Service
@Slf4j
public class ProductAggregatorService {

@Resource(name = "rpcExecutor")
private Executor rpcExecutor;

public CompletableFuture<ProductDetailVo> getProductDetailAsync(Long productId) {
// 1. 并发调用商品基础服务
CompletableFuture<ProductInfo> infoFuture = CompletableFuture.supplyAsync(
() -> productRpcService.getInfo(productId), rpcExecutor)
.orTimeout(1500, TimeUnit.MILLISECONDS)
.exceptionally(ex -> {
log.warn("获取商品基础信息超时/失败, id: {}", productId, ex);
return ProductInfo.defaultFallback(); // 兜底降级
});

// 2. 并发调用库存服务
CompletableFuture<StockInfo> stockFuture = CompletableFuture.supplyAsync(
() -> stockRpcService.getStock(productId), rpcExecutor)
.orTimeout(1000, TimeUnit.MILLISECONDS)
.exceptionally(ex -> StockInfo.defaultFallback());

// 3. 聚合双路结果
return infoFuture.thenCombineAsync(stockFuture, (info, stock) -> {
ProductDetailVo vo = new ProductDetailVo();
vo.setInfo(info);
vo.setStock(stock);
return vo;
}, rpcExecutor).whenComplete((vo, ex) -> {
if (ex != null) {
log.error("商品详情聚合异常, id: {}", productId, ex);
Metrics.counter("product.detail.error").increment();
}
});
}
}